﻿# # -*- coding: utf-8 -*-  
import time
from datetime import datetime, timedelta
import random
import cgi
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm,PasswordChangeForm
from microblog.backend.forms import MyUserSettingsForm, MyUserCreationForm
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render_to_response
from django.utils import simplejson
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from microblog.backend.models import Member, Topic, FollowRelation, Mail, Notice
from django.utils.encoding import smart_unicode
from urllib2 import unquote
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db.models import Q
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.template import RequestContext as RC
from django.core.exceptions import ObjectDoesNotExist,MultipleObjectsReturned
from microblog.utils.decorator import render_to

def backend_proc(request):
    try:
        followed = FollowRelation.objects.filter(user=request.user)[:12]
        follower = FollowRelation.objects.filter(follower=request.user)[:12]
    except:
        followed = 0
        follower = 0
        
    members = Member.objects.all()

    try:
        notices = Notice.objects.all().order_by('-created')[:3]
    except:
        notices = 0
    return locals()

@render_to("index.html", backend_proc)
def index(request):
  members = Member.objects.all()
  topics_all = Topic.objects.all().order_by('-created')
  paginator = Paginator(topics_all, 30)
  try:
    page = int(request.GET.get('page', '1'))
  except ValueError:
    page = 1
  try:
    topics = paginator.page(page)
  except (EmptyPage, InvalidPage):
    topics = paginator.page(paginator.num_pages)
  page_type = 'index'
  view_user = request.user
  m = members_view()
  f = follower_view(request)
  n = notices_view()
  return locals()
@render_to("favorite.html", backend_proc)
@login_required
def favorite_view(request):
  topics_all = request.user.fav.all().order_by('-created')
  paginator = Paginator(topics_all, 30)
  try:
    page = int(request.GET.get('page', '1'))
  except ValueError:
    page = 1
  try:
    topics = paginator.page(page)
  except (EmptyPage, InvalidPage):
    topics = paginator.page(paginator.num_pages)
  page_type = 'favorite'
  view_user = request.user
  return locals()

@login_required
def setfav_view(request):
  assert(request.method =='POST' and request.is_ajax() == True)
  topic = Topic.objects.get(pk=int(request.POST['id']))
  if request.user in topic.favorites.all():
    topic.favorites.remove(request.user)
    response = HttpResponse('unfav')
  else:
    topic.favorites.add(request.user)
    response = HttpResponse('fav')
  return response


@login_required
def follow_member(request):
  assert(request.method=='POST' and request.is_ajax()==True)
  try:
    follower = User.objects.get(pk=int(request.raw_post_data))
    my_follower_ship = FollowRelation.objects.filter(user=request.user, follower=follower)
    if len(my_follower_ship):
      my_follower_ship.delete()
    else:
      follow_relation = FollowRelation(user=request.user, follower=follower)
      follow_relation.save()
    return HttpResponse('success')
  except:
    return HttpResponse('fail')

@login_required
def delete_topic(request):
  assert(request.method=='POST' and request.is_ajax()==True)
  topic = Topic.objects.get(pk=int(request.POST['id']))
  if topic.author == request.user:
    topic.delete()
    return HttpResponse('success')
  else:
    return HttpResponse('fail')

@login_required
def post_topic(request):
  assert(request.method=='POST' and request.is_ajax()==True)
  content = smart_unicode(request.raw_post_data)
  topic = Topic(content=content, author=request.user)
  topic.save()
  response = HttpResponse(cgi.escape(topic.content))
  return response
  
@login_required
def modify_topic(request):
  assert(request.method=='POST' and request.is_ajax()==True)
  related_topic = Topic.objects.get(pk=int(request.POST['id']))
  related_topic.content = request.POST['content']
  related_topic.save()
  response = HttpResponse(cgi.escape(related_topic.content))
  return response

@login_required
def post_daily_topic(request):
  assert(request.method=='POST' and request.is_ajax()==True)
  content = smart_unicode(request.raw_post_data)
  now = datetime.now()
  try:
      topic = Topic.objects.filter(Q(dailyreport=True)&Q(author=request.user)).get(created__range=(now-timedelta(minutes=now.minute,hours=now.hour), now))
      print topic.created
      return HttpResponse(cgi.escape("1"));
  except(ObjectDoesNotExist):
      topic = Topic(content=content, author=request.user, dailyreport=True)
      topic.save()
      return HttpResponse(cgi.escape(topic.content))
  except(MultipleObjectsReturned):
      return HttpResponse(cgi.escape("1"));

@login_required
def post_conversation(request):
  assert(request.method=='POST' and request.is_ajax()==True)
  related_topic = Topic.objects.get(pk=int(request.POST['id']))
  topic = Topic(content=request.POST['content'], author=request.user,conversation=related_topic)
  topic.save()
  related_topic.created = datetime.now()
  print related_topic.created
  related_topic.save()
  response = HttpResponse(cgi.escape(topic.content))
  return response

@login_required
def settings_view(request):
  try:
    info = Member.objects.get(user=request.user)
  except:
    info = Member(user=request.user)
  if request.method == 'POST':
    info_form = MyUserSettingsForm(request.POST, request.FILES, instance=info)
    password_form = PasswordChangeForm(request.user,request.POST)
    if info_form.is_valid():
      info_form = info_form.save()
    if password_form .is_valid():
      password_form.clean_old_password()
      password_form  = password_form.save()
    return HttpResponseRedirect("/selfsettings/")
  else:
    info_form = MyUserSettingsForm(instance=info)
    password_form = PasswordChangeForm(request.user,request.GET)
  return render_to_response("settings.html", {
    'info_form':info_form,
    'password_form':password_form,
  },context_instance=RC(request))

@render_to("self.html", backend_proc)
@login_required
def self_view(request):
  if request.method == 'GET':
    try:
      followed = FollowRelation.objects.filter(user=request.user)[:12]
      follower = FollowRelation.objects.filter(follower=request.user)[:12]
    except:
      followed = 0
      follower = 0
    topics_all = Topic.objects.filter(Q(author=request.user)|Q(conversation__author=request.user)).order_by('-created')
    topics_count = topics_all.count()
    paginator = Paginator(topics_all, 10)
    try:
      page = int(request.GET.get('page', '1'))
    except ValueError:
      page = 1
    try:
      topics = paginator.page(page)
    except (EmptyPage, InvalidPage):
      topics = paginator.page(paginator.num_pages)
    page_type = 'self'
    view_user = request.user
    f = follower_view(request)
    m = members_view()
  return locals()

@render_to("member.html", backend_proc)
@login_required
def member_view(request, user_name):
  if request.method == 'GET':
    view_user = User.objects.get(username=user_name)
    my_follower_ship = FollowRelation.objects.filter(user=request.user).filter(follower=view_user)
    topics_all = Topic.objects.filter(author=view_user).order_by('-created')
    topics_count = topics_all.count()
    paginator = Paginator(topics_all, 30)
    try:
      page = int(request.GET.get('page', '1'))
    except ValueError:
      page = 1
    try:
      topics = paginator.page(page)
    except (EmptyPage, InvalidPage):
      topics = paginator.page(paginator.num_pages)
    page_type = 'member'
    f = follower_view(request)
    m = members_view()
    is_followed = len(my_follower_ship)
    topics_count = topics_count
  return locals()
  
@login_required
def self_daily_report(request):  
    now = datetime.now()
    date = now - timedelta(days=1)
    return date_daily_report(request, date.month, date.day)

@render_to("m_dailyreport.html", backend_proc)
@login_required
def member_daily_report(request, name):
    if request.method == 'GET':
        visit = User.objects.get(username=name)
        topics_all = Topic.objects.filter(Q(author=visit)& Q(dailyreport=True)).order_by('-created')
        topics_count = topics_all.count()
        paginator = Paginator(topics_all, 30)
        try:
          page = int(request.GET.get('page', '1'))
        except ValueError:
          page = 1
        try:
          topics = paginator.page(page)
        except (EmptyPage, InvalidPage):
          topics = paginator.page(paginator.num_pages)
        users = Member.objects.all()
        view_user = request.user
        now = datetime.now()
        f = follower_view(request)
        m = members_view()
    return locals()

@render_to("m_dailyreport.html", backend_proc)
@login_required
def date_daily_report(request, month, day):
    if request.method == 'GET':
        date = datetime(datetime.now().year,  int(month), int(day))
        topics_all = Topic.objects.filter(Q(created__range=(date, date+timedelta(days=1)))& Q(dailyreport=True)).order_by('-created')
        topics_count = topics_all.count()
        f = follower_view(request)
        m = members_view()
        paginator = Paginator(topics_all, 30)
        try:
          page = int(request.GET.get('page', '1'))
        except ValueError:
          page = 1
        try:
          topics = paginator.page(page)
        except (EmptyPage, InvalidPage):
          topics = paginator.page(paginator.num_pages)
        dates = []
        for i in range(0,7):
            dates.append(datetime.now() - timedelta(days=i))
        view_user = request.user
    return locals()
    
def savetxt(request,q):
    f = file('static/a.txt', 'w+')
    f.write(q)
    text = "fsdfsdfasdfasd"
    return HttpResponse(text)

def follower_view(request):
    try:
        followed = FollowRelation.objects.filter(user=request.user)[:12]
        follower = FollowRelation.objects.filter(follower=request.user)[:12]
    except:
        followed = 0
        follower = 0
    return locals()

def members_view():
    members = Member.objects.all()
    return locals()

def notices_view():
    try:
        notices = Notice.objects.all().order_by('-created')[:3]
    except:
        notices = 0
    return locals()